package com.zy.listener;

import com.zy.util.EncryptUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.boot.context.event.ApplicationEnvironmentPreparedEvent;
import org.springframework.context.ApplicationListener;
import org.springframework.core.env.*;

import java.util.HashMap;
import java.util.Map;
import java.util.regex.Matcher;

/**
 * @author zhy
 * @date 2025/6/19 17:15
 */
public class EnvironmentListener implements ApplicationListener<ApplicationEnvironmentPreparedEvent> {
    private static final String EUREKA_KEY = "/eureka";
    private static final String EUREKA_AT_KEY = "@";

    @Override
    public void onApplicationEvent(ApplicationEnvironmentPreparedEvent event) {
        ConfigurableEnvironment environment = event.getEnvironment();
        MutablePropertySources propertySources = environment.getPropertySources();

        Map<String, Object> properties = new HashMap<>();
        for (PropertySource<?> propertySource : propertySources) {
            if (propertySource instanceof EnumerablePropertySource) {
                EnumerablePropertySource<?> enumerablePropertySource = (EnumerablePropertySource<?>) propertySource;
                String[] propertyNames = enumerablePropertySource.getPropertyNames();
                for (String propertyName : propertyNames) {
                    String propertyVal = environment.getProperty(propertyName);
                    if (StringUtils.isEmpty(propertyVal)) {
                        continue;
                    }
                    Matcher matcher = EncryptUtil.encryptMatcher(propertyVal);
                    if (!matcher.find()) {
                        continue;
                    }
                    if (propertyVal.contains(EUREKA_KEY) && propertyVal.contains(EUREKA_AT_KEY)) {
                        String ciphertext = matcher.group();
                        String decrypt = EncryptUtil.decrypt(ciphertext);
                        propertyVal = propertyVal.replace(ciphertext, decrypt);
                    } else {
                        propertyVal = EncryptUtil.decrypt(propertyVal);
                    }
                    properties.put(propertyName, propertyVal);
                }
            }
        }
        if (!properties.isEmpty()) {
            PropertySource<?> propertySource = new MapPropertySource("decryptedProperties", properties);
            environment.getPropertySources().addFirst(propertySource);
        }
    }
}
